package cn.smbms.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.RoleService;
import cn.smbms.service.UserService;

@Controller
public class UserController {

	@Resource
	private UserService userService;

	@Resource
	private RoleService roleService;

	@RequestMapping(value = "user/list")
	public String list(@RequestParam(required = false) String queryname,
			@RequestParam(required = false) Integer queryUserRole, @RequestParam(required = false) Integer pageIndex,
			HttpServletRequest request) {
		Integer pageNo = 1;
		Integer pageSize = 5;
		if (pageIndex != null) {
			pageNo = pageIndex;
		}
		List<User> list = userService.findList(queryname, queryUserRole, pageNo, pageSize);

		request.setAttribute("userList", list);

		List<Role> rolelist = roleService.roleList();

		request.setAttribute("roleList", rolelist);

		request.setAttribute("currentPageNo", pageNo);

		

		int count = userService.count(queryname, queryUserRole);
		
		int totalPage = count / pageSize;

		if (count % pageSize != 0) {
			totalPage++;
		}
		request.setAttribute("totalCount", count);
		request.setAttribute("totalPageCount", totalPage);
		return "userlist";
	}


	/**
	 * 新增的角色查询
	 */
	@RequestMapping(value = "useradd")
	@ResponseBody
	public Object add(HttpServletRequest request) {
//		List<Role> list=new ArrayList<Role>();
		List<Role> rolelist = roleService.roleList();
		
//		request.setAttribute("roleList", rolelist);
		
		return rolelist;
	}
	@RequestMapping(value = "avav")
	public String avav(HttpServletRequest request) {	
		return "useradd";
	}

	/**
	 * ����û�
	 */
	@RequestMapping(value = "/user/add.html", method = RequestMethod.POST)
	public String add(User user, HttpServletRequest request, HttpSession session,
			@RequestParam(value = "attach", required = false) MultipartFile attach) {
		String fileName = null;

		if (!attach.isEmpty()) {

			try {

				String oldFileName = attach.getOriginalFilename();// ԭ�ļ���

				String prefix = FilenameUtils.getExtension(oldFileName);// ԭ�ļ���׺

				if (!(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
						|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg"))) {// �ϴ�ͼƬ��ʽ����ȷ
 
					request.setAttribute("uploadFileError", " * �ϴ�ͼƬ��ʽ����ȷ");
					return "useradd";

				}
				int filesize = 500000;
				if (attach.getSize() > filesize) {
					request.setAttribute("uploadFileError", " * �ϴ���С���ó��� 500k");
					return "useradd";
				}

				
				String path = session.getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
				System.out.println(path);
				fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal.jpg";

				File targetFile = new File(path, fileName);

				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}

				
				attach.transferTo(targetFile);
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		user.setIdPicPath(fileName);
		int count = userService.addUser(user);

		if (count == 0) {

			return "useradd";
		}

		return "redirect:/user/list";
	}

	/**
	 * �޸�
	 */
	@RequestMapping(value = "exit.html")
	public String exit(@RequestParam(value = "uid") Integer id, HttpServletRequest request) {
		User user = userService.findListUser(id);

		request.setAttribute("user", user);

		List<Role> list = roleService.roleList();

		request.setAttribute("roleList", list);
		return "usermodify";
	}

	@RequestMapping(value = "prinById.html", method = RequestMethod.POST)
	public String prinById(User user) {
		int count = userService.prinById(user);
		if (count == 0) {
			return "exit.html";
		}
		return "redirect:/user/list";
	}

	@RequestMapping(value = "delete", method = RequestMethod.GET)
	@ResponseBody
	public Object deleteUser(@RequestParam String uid) {
		HashMap<String, Object> rHashMap = new HashMap<String, Object>();
		if (StringUtils.isNullOrEmpty(uid.toString())) {
			rHashMap.put("delResult", "notexist");
		} else {
			boolean result = userService.deleteUser(Integer.parseInt(uid));
			if (result) {
				rHashMap.put("delResult", result);
			} else {
				rHashMap.put("delResult", result);
			}
		}
		return JSONArray.toJSONString(rHashMap);
	}

	/**
	 * ��ѯUserCode�Ƿ��Ѿ�����
	 */
	@RequestMapping(value = "userCodeExist")
	@ResponseBody
	public String userCodeExist(String userCode) {
		HashMap<String, Object> map = new HashMap<String, Object>();

		boolean result = userService.userCodeExit(userCode);

		if (result == true) {
			map.put("userCode", "exist");
		} else {
			map.put("userCode", "no");
		}
		return JSONArray.toJSONString(map);
	}

	/**
	 * ʹ��ajax��ѯ�û�����
	 */
	@RequestMapping(value="viewJson/{uid}")
	@ResponseBody
	public Object viewJson(@PathVariable(value = "uid")Integer id) {
		User user=userService.findListUser(id);
		//String json =JSONArray.toJSONString(user);
		return user;
	}
	
}
